package net.livingflow.web.resource;

import java.io.StringReader;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import net.livingflow.Constants;
import net.livingflow.model.Flow;
import net.livingflow.model.Pack;
import net.livingflow.model.SharedData;
import net.livingflow.model.Status;
import net.livingflow.model.Account;
import net.livingflow.util.JAXBUtils;
import net.livingflow.web.model.LivingFlow;
import net.livingflow.web.model.XMLFlow;
import net.livingflow.web.model.XMLPack;
import net.livingflow.web.model.XMLUser;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author xueqiang.mi
 * @since 2010-12-19
 */
@Path("/mobile")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class MobileResource extends BaseResource {

	@GET
	@Path("share")
	@Produces("text/plain")
	public String getOnShareEntrance() {
		return "Here is the share entrance for mobile devices!";
	}

	@POST
	@Path("share")
	@Consumes("application/x-www-form-urlencoded")
	@Produces("text/plain")
	public String postShareForm(@FormParam(value = "data") String data) {
		if (StringUtils.isEmpty(data)) {
			return Constants.STATUS_ERROR;
		}
		// 记录数据备份
		SharedData sd = new SharedData();
		sd.setContent(data);
		sharedDataService.add(sd);

		StringReader reader = new StringReader(data);
		LivingFlow livingFlow = JAXBUtils.unmarshal(Constants.JAXB_CONTEXT_PATH, reader);
		XMLUser xUser = livingFlow.getUsers().get(0);
		String userName = xUser.getName();
		String type = xUser.getType();

		Account account = accountService.get(userName);
		if (account == null) {
			accountService.add(userName, type);
			account = accountService.get(userName);
		}

		for (XMLPack xPack : livingFlow.getPacks()) {
			String packName = xPack.getName();
			packName = StringUtils.defaultIfEmpty(packName, Constants.DEFAULT_PACK_NAME);
			Pack pack = packService.getPack(packName, userName);
			if (pack == null) {
				packService.createPackForUser(packName, userName);
				pack = packService.getPack(packName, userName);
			}

			for (XMLFlow xFlow : xPack.getFlows()) {
				Flow f = new Flow();
				f.setName(xFlow.getName());
				f.setType(xFlow.getType());
				f.setContent(xFlow.getContent());
				f.setStatus(Status.MOBILE);
				f.setPackId(pack.getId());
				f.setOwner(userName);
				flowService.add(f);
			}
		}
		return Constants.STATUS_OK;
	}
}
